package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.POIUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/ordersetting")
public class OrderSettingController {

    @Reference
    private OrderSettingService orderSettingService;

    @RequestMapping("/editNumber")
    public Result editNumber(@RequestBody OrderSetting orderSetting) {
        try {
            orderSettingService.editNumber(orderSetting);
            return Result.success(MessageConstant.ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(MessageConstant.ORDERSETTING_FAIL);
        }
    }

    /**
     * Excel文件上传，并解析文件内容保存到数据库
     *
     * @param excelFile
     * @return
     */
    //文件上传
    @RequestMapping("/upload")
    public Result upload(@RequestParam("excelFile") MultipartFile excelFile) {
        try {
            //读取Excel文件
            List<String[]> strings = POIUtils.readExcel(excelFile);
            for (String[] string : strings) {
                OrderSetting orderSetting = new OrderSetting(new Date(string[0]), Integer.parseInt(string[1]));
                orderSettingService.editNumber(orderSetting);
            }

            return Result.success(MessageConstant.ORDERSETTING_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.error(MessageConstant.ORDERSETTING_FAIL);
    }
    @RequestMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(String date) {
        try {
            List<OrderSetting> orderSettings= orderSettingService.getOrderSettingByMonth(date);
            return Result.success(MessageConstant.QUERY_ORDER_SUCCESS,orderSettings);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
